package com.bittech.servlet.smallfileserver.web.config.listener;


import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

/**
 * Author: secondriver
 * Created: 2018/8/27
 */
@WebListener
public class MongoDBClientLoaderListener implements ServletContextListener {
    
    public static MongoDBClient mongoDBClient;
    
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        String url = servletContext.getInitParameter("mongo_url");
        if (url == null || url.equals("")) {
            url = "mongodb://localhost:27017";
        }
        String databaseName = servletContext.getInitParameter("mongo_databaseName");
        if (databaseName == null || databaseName.equals("")) {
            databaseName = "small";
        }
        if (mongoDBClient == null) {
            mongoDBClient = new MongoDBClient(url, databaseName);
        }
    }
    
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        mongoDBClient = null;
    }
    
    public final class MongoDBClient {
        
        private MongoClient mongoClient;
        
        private GridFSBucket gridFSBucket;
        
        private MongoDBClient(String uri, String databaseName) {
            this.mongoClient = MongoClients.create(uri);
            gridFSBucket = GridFSBuckets.create(this.mongoClient.getDatabase(databaseName));
        }
        
        public GridFSBucket getGridFS() {
            return gridFSBucket;
        }
        
        public MongoClient getMongoClient() {
            return mongoClient;
        }
    }
}